var config = require('./config');

App({
  onLaunch: function() {
    console.info('加载小程序中...');
    wx.showLoading({
      title: '正在获取信息',
      mask: false
    });
    var that = this;
    wx.showLoading({
      title: '登录中',
      mask: false
    });
    this.checkLogin();
  },

  //检测是否登录
  checkLogin: function() {
    console.info('正在检查登陆状态...');
    var skey = wx.getStorageSync('skey');
    if (skey) {
      console.log('获取用户信息中...');
      this.getUserInfo();
    } else {
      console.log('登陆中...');
      this.login();
    }
  },

  //登录
  //step1，调用wx.login获取code
  //step2，发送code到腾讯云，并且返回第三方skey，存储到本地
  //step3，获取用户信息
  login: function() {
    console.info('微信登陆中...');
    var that = this;
    wx.login({
      success: function(res) {
        // 登录请求
        console.log('微信登陆成功');
        console.log('小程序登陆中...')
        wx.request({
          url: config.host + '/login2',
          data: {
            code: res.code
          },
          success: function(res) {
            console.log('小程序登陆成功')
            console.log(res);
            var skey = res.data.skey;
            console.info('您的skey为', skey);
            //如果获取不到skey，则重试
            if (!skey) {
              console.info('获取skey失败，重新登录中...',skey);
              that.login();
              return;
            }
            wx.setStorageSync('skey', skey);
            that.getUserInfo();
          }
        })
      },
    });
  },

  //获取用户信息
  //对于未登录用户，重新登录
  //对于未注册用户，注册新用户
  //对于已注册用户，全局写入用户信息
  getUserInfo: function() {
    var that = this;
    this.request({
      url: '/user2',
      success: function(res) {
        console.log('信息获取返回结果：');
        console.log(res);
        // 未登录
        if (res.statusCode === 401) {
          console.log('用户未登录，正在登陆中...');
          that.login();
        } else {
          // 未注册用户
          if (res.statusCode === 400) {
            console.log('未注册用户，进入注册页面')
            wx.reLaunch({
              url: './pages/register/register',
            })
            console.log(400)
          } else {
            console.log('获取用户信息成功！');
            var interest = []
            interest[0] = res.data.interest1
            interest[1] = res.data.interest2
            interest[2] = res.data.interest3
            interest[3] = res.data.interest4
            interest[4] = res.data.interest5
            that.globalData.userInfo = {
              open_id: res.data.open_id,
              name: res.data.name,
              school: res.data.school,
              interest: interest
            }
            wx.hideLoading();
          }
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },

  //注册用户
  //在User表中添加记录
  //授权失败写入默认用户信息，否则写入通过wx.getUserInfo获取的用户信息
  registerUser: function() {
    console.log(this.globalData);
    var that = this;
    wx.getUserInfo({
      success: function(res) {
        console.log('获取用户微信信息成功:');
        console.log(res);
        that.globalData.userInfo.name = res.userInfo.nickName;
        that.request({
          url: '/user2',
          method: 'POST',
          data: that.globalData.userInfo,
          success: function(res) {
            console.log('注册成功:');
            console.log(res);
            wx.hideLoading();
            wx.redirectTo({
              url: '../index/index',
            })
          },
          fail: function() {
            var th = that;
            console.log('请求发送成功，但注册失败');
            wx.showModal({
              title: '注册失败',
              content: '是否重试？',
              confirmText: '是',
              cancelText: '否',
              success: function(res) {
                if (res.confirm) {
                  th.register();
                } else if (res.cancel) {


                  //进入游客模式



                }
              }
            });
          }
        });
      },
      //授权失败，用默认值注册
      fail: function(res) {
        console.log('注册请求发送失败：');
        console.log(res);
        wx.showLoading({
          title: '服务器出错，注册失败，正在进入游客模式...',
        })
        setTimeout(function() {



          //进入游客模式



          wx.hideLoading()
        }, 2000)
      }
    })
  },

  //封装wx.request，自动添加host以及API版本号
  request: function(obj) {
    var skey = wx.getStorageSync('skey');
    console.log(skey);
    obj.url = config.host + obj.url;
    obj.header = {
      skey: skey,
      version: config.apiVersion
    };
    console.log(obj);
    return wx.request(obj);
  },

  //全局数据维护
  globalData: {
    
    //默认值
    userInfo: {
      open_id: null,
      name: '游客',
      school: '',
      interest: [null, null, null, null, null]
    },
    school_list: ['北京理工大学珠海学院'],
    interest_list: ['体育', '文艺', '展会', '市场', '讲座', '户外', '公益', '娱乐', '比赛', '表演', '科技', '美食'],
  }
})